
package com.roomio.util;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;

import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This class is converts a Double to a double-digit String (and vise-versa) by
 * BeanUtils when copying properties. Registered for use in BaseAction.
 * 
 * <p>
 * <a href="CurrencyConverter.java.html"><i>View Source</i></a>
 * </p>
 * 
 * @author <a href="mailto:og.tech79@gmail.com">Shailendra Sinha</a>
 */
public class CurrencyConverter implements Converter {
	private static final Logger log = LoggerFactory.getLogger(CurrencyConverter.class);
	protected final DecimalFormat formatter = new DecimalFormat("###,###.00");

	/**
	 * Convert a String to a Double and a Double to a String
	 * 
	 * @param type
	 *            the class type to output
	 * @param value
	 *            the object to convert
	 * @return object the converted object (Double or String)
	 */
	public final Object convert(final Class type, final Object value) {
		// for a null value, return null
		if (value == null) {
			return null;
		} else {
			if (value instanceof String) {
				if (log.isDebugEnabled()) {
					log.debug("value (" + value + ") instance of String");
				}

				try {
//					if (StringUtil.isEmpty(value)) {
//						return null;
//					}

					if (log.isDebugEnabled()) {
						log.debug("converting '" + value + "' to a decimal");
					}

					// formatter.setDecimalSeparatorAlwaysShown(true);
					Number num = formatter.parse(String.valueOf(value));

					return new Double(num.doubleValue());
				} catch (ParseException pe) {
					pe.printStackTrace();
				}
			} else if (value instanceof Double) {
				if (log.isDebugEnabled()) {
					log.debug("value (" + value + ") instance of Double");
					log.debug("returning double: " + formatter.format(value));
				}

				return formatter.format(value);
			}
		}

		throw new ConversionException("Could not convert " + value + " to " + type.getName() + "!");
	}

	/**
	 * To set the amount to 2 decimal value
	 * 
	 * @param amount
	 * @return
	 */
	public static final BigDecimal formatCurrency(BigDecimal amount) {
		if (amount != null)
			return amount.setScale(2, BigDecimal.ROUND_HALF_UP);
		else
			return amount;

	}

	public static final String convertToString(BigDecimal value) {
		BigDecimal amount = new BigDecimal(0.00);
		if (value != null) {
			amount = formatCurrency(value);
		} else {
			return " ";
		}
		return amount.toString();
	}

	public static final String convertToString(Double value) {
		NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();
		String amount;
		if (value != null) {
			amount = currencyFormatter.format(value.doubleValue());
		} else {
			return " ";
		}
		return amount;
	}

}
